/*
 * @Description: 发送逻辑
 */
import sendCommon from '@/handles/common/send';
import globalMethods from '@/plugins/methods';
import globalData from "@/plugins/data";
import {fireEvent, getCollEventParams} from '@/handles/common/sdk'
import emitter from "@/plugins/global-callback";
import { useBaseInfoStore } from '@/store/modules/base-info';

//发送
async function sendCollaboration(resolve, reject) {
    //提取参数
    const { summaryId } = sendCommon;
    //获取正文iframe对象
    var fnx = sendCommon.useTemplate.zwIframe.contentWindow;
    const useBaseInfo = sendCommon.useBaseInfo;

    const { summary, template } = useBaseInfo.baseInfo.businessData;
    //如果正文iframe对象不存在 则直接返回
    if (!fnx) {
        globalMethods.message.error($.i18n('collaboration.common.content.loading.js')); //正文未加载完成，请稍后重试
        return resolve();
    }

    // 检查流程期限是不是比当前日期早
    if (useBaseInfo.sendCheckDeadlineDatetime()) return resolve();
    //校验密级 + 标题
    if (!useBaseInfo.checkSecret() || !useBaseInfo.validateSubject()|| !useBaseInfo.validateAttachmentUploading()) return resolve();
    let cap4 = useBaseInfo.baseInfo.zwIframe.isCap4;
    //非cap4 且 不是工作流二次提交确认
    if (!cap4 && !useBaseInfo.weekSubmit) {
        //用于快速选人生成流程图信息
        await emitter.publish("sendFreeCol");
    }
    //判断流程是否为空
    if (!useBaseInfo.validateProcess()) return resolve();
    let result = await new Promise((resolve) =>{
       useBaseInfo.validateSupervise(resolve);
    });
    if (result===false) return resolve();

    fnx.contentAPI.setSaveContentParam(
        summary.id, //协同id
        useBaseInfo.formInfo.subject.value,
        template?.id, //当前模板id
        useBaseInfo.baseInfo.secretLevel.value //选择的密级
    );
    

    //remind_workflow_start_department_id
    sendCommon.confirmWorkflowStartDepartment(resolve,  function () {
        const businessData = useBaseInfoStore().baseInfo?.businessData || {};
        const eventParams = getCollEventParams(businessData, globalData);
        // 触发事件
        fireEvent('beforePreSubmit', {
            error: resolve,
            ...eventParams
        }).then(result => {
            if (result === true) {
                return fireEvent('beforSendColl', eventParams);
            }
            return false;
        }).then(result => {
            if (result === true) {
                console.log('confirmWorkflowStartDepartment',useBaseInfo.needCheckRule)
                sendCommon.send({resolve, needCheck: useBaseInfo.needCheckRule});
            } else {
                resolve();
            }
        }).catch(e => {
            console.log('confirmWorkflowStartDepartment error', e);
        });
        
    });
}

export default () =>
    new Promise(async (resolve, reject) => {
        sendCommon.useBaseInfo.setIsHideGlobalLoading(false);
        await sendCollaboration(resolve, reject);
    }).finally(() => {
        sendCommon.useBaseInfo.setIsHideGlobalLoading();
    });
